package com.jmhy.sdk.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jmhy.sdk.common.JiMiSDK;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.http.ApiAsyncTask;
import com.jmhy.sdk.http.ApiRequestListener;
import com.jmhy.sdk.model.Guest;
import com.jmhy.sdk.model.LoginMessage;
import com.jmhy.sdk.sdk.JmhyApi;
import com.jmhy.sdk.utils.FragmentUtils;
import com.jmhy.sdk.utils.Utils;

public class JmUserLoginOrRegAccountFragment8 extends JmBaseFragment implements
        View.OnClickListener {

    private EditText et_input_account, et_input_pwd;
    private ImageView down_eye_btn;
    private Button btn_reback, btn_login;
    private TextView tv_register_account, tv_forgot_pwd;
    private boolean isShowPwd = false;
    private String account;
    private ApiAsyncTask mLoginTask;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        view = inflater.inflate(AppConfig.resourceId(getActivity(),
                "jm_account_login_8", "layout"), container, false);
        view.setClickable(true);

        if (getArguments() != null) {
            String param = getArguments().getString("account");
            account = param;
        }
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {


        et_input_account = getView().findViewById(AppConfig.resourceId(getActivity(), "et_input_account", "id"));
        if (!Utils.judgeStrNull(account)) {
            et_input_account.setText(account);
        }

        et_input_pwd = getView().findViewById(AppConfig.resourceId(getActivity(), "et_input_pwd", "id"));
        et_input_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());

        btn_login = getView().findViewById(AppConfig.resourceId(getActivity(), "btn_login", "id"));
        btn_login.setOnClickListener(this);

        down_eye_btn = getView().findViewById(AppConfig.resourceId(getActivity(), "down_eye_btn", "id"));
        down_eye_btn.setOnClickListener(this);

        tv_register_account = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_register_account", "id"));
        tv_register_account.setOnClickListener(this);

        tv_forgot_pwd = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_forgot_pwd", "id"));
        tv_forgot_pwd.setOnClickListener(this);

        btn_reback = getView().findViewById(AppConfig.resourceId(getActivity(), "btn_reback", "id"));
        btn_reback.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == AppConfig.resourceId(getActivity(), "down_eye_btn", "id")) {

            if (!isShowPwd) {
                isShowPwd = true;
                et_input_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                down_eye_btn.setImageResource(AppConfig.resourceId(getActivity(),
                        "jm_open_eye", "drawable"));
            } else {
                isShowPwd = false;
                et_input_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                down_eye_btn.setImageResource(AppConfig.resourceId(getActivity(),
                        "jm_close_eye", "drawable"));
            }

        } else if (id == AppConfig.resourceId(getActivity(), "tv_register_account", "id")) {
            Fragment selectAccountLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_REGISTER_TAG);
            replaceFragmentToActivity(getFragmentManager(),
                    selectAccountLoginFragment,
                    AppConfig.resourceId(getActivity(), "content", "id"));
        } else if (id == AppConfig.resourceId(getActivity(), "btn_login", "id")) {
            startLogin();

        } else if (id == AppConfig.resourceId(getActivity(), "tv_forgot_pwd", "id")) {


            turnToIntent(AppConfig.FPWD);

        } else if (id == AppConfig.resourceId(getActivity(), "btn_reback", "id")) {
            Fragment selectAccountLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_SELECT_LOGIN_TYPE_TAG);

            replaceFragmentToActivity(getFragmentManager(),
                    selectAccountLoginFragment,
                    AppConfig.resourceId(getActivity(), "content", "id"));
        }

    }

    private void startLogin() {
        // 登陆
        String username = et_input_account.getText().toString().trim();
        String pwd = et_input_pwd.getText().toString().trim();

        if (TextUtils.isEmpty(username)) {
            showMsg(AppConfig.getString(getActivity(), "user_hintuser_msg"));
            return;

        }
        if (TextUtils.isEmpty(pwd)) {
            showMsg(AppConfig.getString(getActivity(), "user_hintpwd_msg"));
            return;
        }
        login(username, pwd);
    }


    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            switch (msg.what) {
                case AppConfig.FLAG_FAIL:
                    String resultmsg = (String) msg.obj;
                    showMsg(resultmsg);
                    break;
                case AppConfig.AUTO_LOGIN_SUCCESS:
                case AppConfig.LOGIN_SUCCESS:
                    LoginMessage result = (LoginMessage) msg.obj;
                    showUserMsg(result.getUname());
                    AppConfig.USERURL = Utils.toBase64url(result.getFloat_url_user_center());
                    String url = Utils.toBase64url(result.getShow_url_after_login());
                    if (TextUtils.isEmpty(url)) {
                        url = Utils.toBase64url(result.getShow_url_popup());
                    }
                    turnToNotice(url);
                    getActivity().finish();
                    break;

                case AppConfig.GUEST_lOGIN_SUCCESS:
                    Guest guest = (Guest) msg.obj;
                    String murl = Utils.toBase64url(guest.getShow_url_after_login());
                    if (TextUtils.isEmpty(murl)) {
                        murl = Utils.toBase64url(guest.getShow_url_popup());
                    }

                    if (!TextUtils.isEmpty(guest.getUpass())) {
                        Bundle args = new Bundle();
                        // Log.i("kk",mobileUser.getMoblie())
                        args.putString("username", guest.getUname());
                        args.putString("upass", guest.getUpass());
                        args.putString("msg", guest.getMessage());
                        args.putString("gametoken", guest.getGame_token());
                        args.putString("openid", guest.getOpenid());
                        args.putString("url", murl);
                        Fragment mJmSetUserFragment = FragmentUtils.getJmSetUserFragment(getActivity(), args);
                        replaceFragmentToActivity(getFragmentManager(), mJmSetUserFragment, AppConfig.resourceId(getActivity(), "content", "id"));
                    } else {
                        wrapaLoginInfo("success", guest.getMessage(), guest.getUname(), guest.getOpenid(), guest.getGame_token());
                        turnToNotice(murl);
                        getActivity().finish();
                    }
                    break;
            }
        }
    };

    private void login(final String userName, final String passWord) {
        mLoginTask = JmhyApi.get().starusreLogin(getActivity(), AppConfig.appKey, userName, passWord, new ApiRequestListener() {

            @Override
            public void onSuccess(Object obj) {
                // TODO Auto-generated method stub
                if (obj != null) {
                    LoginMessage loginMessage = (LoginMessage) obj;

                    if (loginMessage.getCode().equals("0")) {
                        mSeference.saveAccount(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        AppConfig.saveMap(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        Utils.saveUserToSd(getActivity());
                        wrapaLoginInfo("success", loginMessage.getMessage(), loginMessage.getUname(), loginMessage.getOpenid(), loginMessage.getGame_token());
                        sendData(AppConfig.LOGIN_SUCCESS, obj, handler);

                    } else {
                        sendData(AppConfig.FLAG_FAIL, loginMessage.getMessage(), handler);
                        JiMiSDK.reportRequestErrorAction(getActivity(), "sdk_user_login_error", loginMessage.getCode(), loginMessage.getMessage());

                    }
                } else {
                    sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
                }
            }

            @Override
            public void onError(int statusCode) {
                // TODO Auto-generated method stub
                sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
            }
        });
    }

    @Override
    public void onDestroy() {
        if (mLoginTask != null) {
            mLoginTask.cancel(false);
        }
        super.onDestroy();
    }
}
